//
//  YXYPictureView.swift
//  SinaWeibo
//
//  Created by 袁向阳 on 16/6/30.
//  Copyright © 2016年 YXY.cn. All rights reserved.
//

import UIKit

private let pictureViewCellReuseId: String = "pictureViewCellReuseId"
private let itemMargin: CGFloat = 5

class YXYPictureView: UICollectionView {
    
    // 流水布局
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    // 供外界设置的图片数组
    var pic_urls: [YXYPictureInfo]? {
        didSet {
            // 更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(setUpCell())
            }
            // 给数字label赋值
            numLabel.text = "\(pic_urls?.count ?? 0)"
            reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setUpCollectionView()
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 注册cell
    private func setUpCollectionView () {
        registerClass(YXYPictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellReuseId)
    }
    
    // MARK: - 设置collectionView的大小和item的大小
    private func setUpCell () -> CGSize {
        
        let cellWH: CGFloat = (UIScreen.mainScreen().bounds.size.width - constantMargin*2 - itemMargin*2) / 3
        
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.scrollDirection = .Horizontal
        
        // 如果为 4 个，则显示 2 行 2 列
        // 列数
        let count = pic_urls?.count
//        count = 4
        let col = count == 4 ? 2 : ( count >= 3 ? 3 : count)
        // 行数
        let row = count == 4 ? 2 : ((count! - 1) / 3 + 1)
        
        // collectionView的宽
        let width = (CGFloat(col!) - 1) * itemMargin + CGFloat(col!) * cellWH
        // collectionView的高
        let height = (CGFloat(row) - 1) * itemMargin + CGFloat(row) * cellWH
        
        let size = CGSize(width: width, height: height)
        return size
    }
    
    // MARK: - 添加子控件
    private func setUpUI () {
        backgroundColor = UIColor(red: 237/255.0, green: 237/255.0, blue: 237/255.0, alpha: 1.0)
        
        self.dataSource = self
        
        addSubview(numLabel)
        numLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }
    
    // 提示数字label
    lazy var numLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.redColor()
        lab.font = UIFont.systemFontOfSize(35)
        return lab
    }()
}

extension YXYPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = pic_urls?.count
//        count = 4
        return count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellReuseId, forIndexPath: indexPath) as? YXYPictureViewCell
        
        cell!.backgroundColor = randomColor()
        cell?.pic = pic_urls![indexPath.item].thumbnail_pic
        
        return cell!
    }
}

// MARK: - 自定义cell
class YXYPictureViewCell: UICollectionViewCell {
    
    // 供外界设置图片
    var pic: String? {
        didSet {
            imageView.sd_setImageWithURL(NSURL(string: pic!), placeholderImage: UIImage(named: "timeline_card_top_background"))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 添加子控件
    private func setUpUI () {
        contentView.addSubview(imageView)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
    }
    
    // 图片视图
    lazy var imageView: UIImageView = {
        let img = UIImageView(image: UIImage(named: "timeline_card_top_background"))
        
        // 指定图片填充方式
        img.contentMode = .ScaleAspectFill
        img.clipsToBounds = true
        
        return img
    }()
}
